<!-- @format -->

<!--添加修改用户信息-->
<template>
    <a-modal v-model="showAddTable" :width="640"
             title="用户导入"
             :maskClosable="false"
             :destroyOnClose="true" @cancel="cancelApply">
        <a-form :form="form" @keydown.native.enter.prevent="saveApply" class="modelSearch">
            <a-form-item v-bind="formStyle" label="组织机构" required v-if="perms.sysOrg">
                <a-tree-select
                        style="width: 100%"
                        :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                        :treeData="orgTree"  placeholder="请选择组织机构"
                        v-decorator="['orgId', { rules: [{ required: true, message: '请选择组织机构' }] }]">
                    <span style="color: #08c" slot="title" slot-scope="{key, title}">{{title}}</span>
                </a-tree-select>
            </a-form-item>
            <a-form-item v-bind="formStyle" label="角色" required v-if="perms.addUserRole">
                <a-select
                        placeholder="请选择角色"  :disabled="!title" :showArrow="title"
                        v-decorator="['roleId',  { rules: [{ required: true, message: '请选择角色' }] }]"
                >
                    <a-select-option v-for="item in roleOpts" :value="item.value" :key="item.value">{{ item.label }}</a-select-option>
                </a-select>
            </a-form-item>
          <a-form-item label="文件：" class="handFile" v-bind="formStyle"  style="position: relative" required :extra="errorMsg">
            <a-input v-model="userListFileName" read-only style="width: 280px; float: left"
                     disabled :maxlength="100" placeholder="请选择用户文件" />
            <a href="javascript:;" style="background-color: #35bbd4 ;color: #ffffff">
              <input ref="userListFile" type="file" name="userListFile"
                     :accept="accept"
                     @change="onChangeFile($event,'userListFile')"
                     required />选择文件
            </a>
          </a-form-item>
          <a-form-item v-bind="formStyle" label="模板下载" v-show="title">
            <a-button type="primary" @click="downloadImportTemplate">下载用户导入模板</a-button>
          </a-form-item>
            <a-form-item v-bind="formStyle" label="登录密码" v-show="title">
                <span style="color:rgba(221,0,0,0.9);">如果导入密码为空，则默认为初始化密码为Cau19121111</span>
            </a-form-item>
        </a-form>
      <!-- 登录页驱动下载处理 -->
      <iframe id="templateFile" title="下载用户导入模板" style="display: none"></iframe>

        <div slot="footer">
            <a-button type="default" @click="cancelApply('sysUserDtos')">取消</a-button>
            <a-button type="primary" @click="saveApply">确定</a-button>
        </div>
      <div class="spinBox" v-if="spinning">{{spinText}}</div>
    </a-modal>

</template>

<script>
import verify from 'libs/verify'
import util from '@/libs/util.js'

export default {
    name: 'importUser',
    data() {
        return {
            form: this.$form.createForm(this),
            verify,
            showAddTable: false,
            roleType: '',
            flags: '',
          spinning:false,
          spinText:'请稍后...',
            countOrgChange: 0,
            originalData: {},
            selectedNode: {},
            /*选中的记录*/
            checkData: [],
            orgTreeData: [],
            roleOpts: [],
          errorMsg: '',
          accept:'.xls',
          userListFile:'',
          userListFileName:'',
            isUKeyLogin: sessionStorage.getItem ('isUKeyLogin'),
        }
    },
    computed: {
        formStyle() {
            return this.$store.state.common.formStyle
        }
    },
    props: {
        sysUserDtos: {
            type: Object,
            required: true
        },
        title: {
            type: Boolean,
            required: true
        },
        orgTree: {
            type: Array,
            required: true
        },
        perms: {
            type: Object,
            required: true
        },
        fromRoleOpts: {
            type: Array,
            required: true
        }
    },
    watch: {
        orgTree(value) {
            this.orgTreeData = value
        },
        sysUserDtos(value) {
            this.countOrgChange = 0
            this.selectedNode = {
                id: value.orgId,
                name: value.orgName
            }
        },
        fromRoleOpts: {
            handler(val) {
                this.roleOpts = val
            },
            deep: true,
            immediate: false
        }
    },
    methods: {

      /**
       * 选择文件
       */
      onChangeFile (e, name) {
        let _this = this;
          _this.userListFile = e.target.files[0];
          _this.userListFileName = e.target.files[0].name;
          _this.errorMsg = '';
          let indexDot = _this.userListFileName.lastIndexOf('.');
          if (_this.userListFileName.substr(indexDot + 1, 3) !== 'xls') {
            _this.errorMsg = '请上传xls文件';
            _this.userListFile = '';
            _this.userListFileName = ''
          }
      },

        /**
         * Function    : showModal
         * Description : 打开弹框
         * Input       : none
         * Return      : none
         */
        showModal() {
            this.showAddTable = true
        },

        /**
         * Function    : showEdit
         * Description : 编辑时单位显示
         * Input       : opt单个单位所有数据
         * Return      : none
         */
        showEdit(opt) {
            this.showAddTable = true
            this.id = opt.id
            this.$nextTick(() => {
                this.form.setFieldsValue(this.$pick(opt, ['userName', 'name', 'sfzjh','phoneNum']))
            })
            if(this.perms.sysOrg){
                this.$nextTick(() => {
                    this.form.setFieldsValue(this.$pick(opt, ['orgId']))
                })
            }
            if(this.perms.addUserRole){
                this.$nextTick(() => {
                    this.form.setFieldsValue(this.$pick(opt, ['roleId']))
                })
            }
        },
      /**
       * 下载导入的模板
       */
      downloadImportTemplate(){
        document.getElementById ('templateFile').src = '/auth/sysuser/downloadImportSysUserTemplate';
      },

        /**
         * Function    : saveApply
         * Description : 用户信息新增、编辑保存
         * Input       : name
         * Return      : none
         */
        saveApply(e) {
          let _this = this;
            e.preventDefault()
            this.form.validateFields((err, value) => {

              if (_this.userListFileName === '') {
                _this.errorMsg ='请选择xls文件'
              }
              if (_this.errorMsg !== undefined && _this.errorMsg !== '') {
                return
              }
              if (!err) {
                let formData = new FormData ()
                let url = 'sysuser/importSysUser'
                if(_this.isEdit){
                  formData.append ('id', this.id)
                }
                _this.spinning = true
                formData.append ('roleId', value.roleId)
                formData.append ('orgId', value.orgId)
                formData.append ('userListFile', _this.userListFile)
                _this.$uploadPost (url, formData).then (response => {
                  this.showAddTable = false
                  this.roleOpts = []
                  if (response.code === 0) {
                    this.$emit('init')
                    this.$message.success(response.message)
                    this.cancelApply()
                  } else {
                    this.$message.error(response.message)
                  }
                  _this.userListFile = '';
                  _this.userListFileName = ''
                  this.$parent.spinning = false
                  _this.spinning = true
                })
              }
            })
        },

        /**
         * Function    : selectedTreeId
         * Description :
         * Input       : val
         * Return      : none
         */
        selectedTreeId(val) {
            this.$refs['orgId'].resetField()
            this.sysUserDtos.orgId = val.id

            /**
             * 级联查询组织机构下的角色
             */
            /*if (this.countOrgChange > 0) {
          this.$store.dispatch('loadOrgsRolesAct',{orgId : val.id}).then(response => {
            this.roleOpts = response;
            this.sysUserDtos.roleId = '';
          });
        }*/
            this.countOrgChange = 1
        },

        /**
         * Function    : cancelApply
         * Description : 取消弹出框
         * Input       : name
         * Return      : none
         */
        cancelApply() {
            this.showAddTable = false
            let _this = this
          _this.userListFile = '';
          _this.userListFileName = ''
            setTimeout(function() {
                _this.form.resetFields()
                _this.roleOpts = []
            }, 100)
        },

        /**
         * Function    : resetUserPasswd
         * Description : 重置用户密码
         * Input       : none
         * Return      : none
         */
        resetUserPasswd(name) {
            this.$parent.spinning = true
            this.$store.dispatch('resetUserPasswdAct', { userName: this.sysUserDtos.userName }).then(response => {
                this.$parent.spinning = false
                if (response.code === 0) {
                    this.$message.success(response.message)
                    this.showAddTable = false
                    this.roleOpts = []
                    this.$refs[name].resetFields()
                } else {
                    this.$message.error(response.message)
                }
            }).catch(e => {
                this.$parent.spinning = false
            })
        }
    },

    created() {}
}
</script>
<style lang="less">
.showDownStyle{
  font-size: 14px;color: #06f130;cursor: pointer;position:absolute; left:45px; top:335px;margin-left: 3px;
}
</style>
